import { Component, OnInit, Input } from '@angular/core';
import { TreeNode } from 'primeng/api';
import { StatisticsUtilsService } from '../../shared/services/statistics-utils.service';
import * as _ from 'lodash';
import { Router, ActivatedRoute } from '@angular/router';
import { AppSettings, UserRoles } from '../../shared/config/app-settings';
import { UserService } from '../../shared/services/user.service';
@Component({
  selector: 'app-subagent-kpi',
  templateUrl: './subagent-kpi.component.html',
  styleUrls: ['./subagent-kpi.component.scss']
})
export class SubagentKpiComponent implements OnInit {
  currentSessionUser:any = {};
  orgTree: TreeNode[];
  selectedNode: TreeNode;
  @Input("referID")
  referID: string;
  treeSource: TreeNode[];
  selectedCode:string;
  constructor(
    private userService:UserService,
    private statisticsUtilsService: StatisticsUtilsService,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.referID = params['referid']; // (+) converts string 'id' to a number
      // In a real app: dispatch action to load the details here.
      
    });

    
    this.getCurrentUser();
    console.log('this.referID');
    console.log(this.referID);


  }

  ngOnChanges(): void {
    //Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.
    //Add '${implements OnChanges}' to the class.
    this.loadUseragentKPI(this.referID);
  }

  
  getCurrentUser(){
    this.userService.getCurrentUser().subscribe((user)=>{
      this.currentSessionUser = user;
      console.log(user);
      if (this.referID){
        this.selectedCode = this.referID;
        if(this.currentSessionUser.role === UserRoles.AGENT){
          this.loadUserOrgTree(this.referID, 1);
        }else{
          this.loadUserOrgTree(this.referID, 0);
        }
        
        this.loadUseragentKPI(this.referID);
      }
      else{
        this.loadUserOrgTree(AppSettings.rootCode, 0);
      }
    });
  }

  loadUserOrgTree(referID, level) {
    this.statisticsUtilsService.getUserOrgTree(referID, level).subscribe(
      (res) =>{
        this.orgTree = res;
      }
    )
  }

  loadUseragentKPI(referID) {
    
    this.statisticsUtilsService.getSubAgentKPI(referID).subscribe(
      (res) => {
        this.selectedCode = referID;
        this.treeSource = [];
        _.each(res, (agent) => {
          let children = [];
          _.each(agent.saledProperties, (child) => {
            children.push({
              "data": {
                name: `${child.lot}.${child.address}` ,
                current_commission: child.current_commission,
                total_commission: child.total_commission,
                my_referral_paid: child.my_referral_paid
              }
            });
          });
          let agentSource = {
            "data": {
              name: agent.code + `(${agent.name})`,
              current_commission: agent.saledComission.sum_current_commission,
              total_commission: agent.saledComission.sum_total_commission,
              my_referral_paid: agent.saledComission.sum_my_referral_paid
            },
            "children": children
          };
          this.treeSource.push(agentSource);

        });
      });
  }

  onNodeSelect(event) {
    console.log(event.node);
    if(this.currentSessionUser.role === UserRoles.ADMIN){
      this.loadUseragentKPI(event.node.value);
    }
    

  }


}
